package com.aiyige.page.my.message;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.eventbus.EventCommunicatePageRouter;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.eventbus.EventNewMessageChanged;
import com.aiyige.base.eventbus.EventTapBottomItemRefresh;
import com.aiyige.page.my.message.adapter.CommunicateAdapter;
import com.aiyige.page.my.message.event.EventRefreshCommunicatePageChildren;
import com.aiyige.page.my.message.util.MessageUtil;
import com.flyco.tablayout.SlidingTabLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class CommunicatePage extends BaseFragment {

    @BindView(R.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.mainVp)
    ViewPager mainVp;
    Unbinder unbinder;
    CommunicateAdapter communicateAdapter;
    Integer pendingRefreshCommunicatePageChildrenType = null;

    public CommunicatePage() {
        setAutoRegisterEventBus(true);
    }

    public static CommunicatePage newInstance() {
        CommunicatePage communicatePage = new CommunicatePage();
        return communicatePage;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_communicate, container, false);
        unbinder = ButterKnife.bind(this, view);
        communicateAdapter = new CommunicateAdapter(getChildFragmentManager());
        mainVp.setAdapter(communicateAdapter);
        tabLayout.setViewPager(mainVp);
        mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 1) {
                    MessageUtil.consumeAllNewMessage(MessageUtil.MESSAGE_TYPE_CONTACT);
                    updateUnReadMessageView();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Router.unregisterRouterEventBus(this);
        unbinder.unbind();
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        if (pendingRefreshCommunicatePageChildrenType != null) {
            EventBus.getDefault().post(EventRefreshCommunicatePageChildren.newBuilder()
                    .type(pendingRefreshCommunicatePageChildrenType).build());
            pendingRefreshCommunicatePageChildrenType = null;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventNewMessageChanged event) {
        if (tabLayout.getCurrentTab() == 1) {
            MessageUtil.consumeAllNewMessage(MessageUtil.MESSAGE_TYPE_CONTACT);
        }
        updateUnReadMessageView();
        if (event.isDontRequestData()) return;
        Integer childType;
        switch (event.getType()) {
            case MessageUtil.MESSAGE_TYPE_SYSTEM:
            case MessageUtil.MESSAGE_TYPE_ORDER:
            case MessageUtil.MESSAGE_TYPE_INTERACT:
                childType = EventRefreshCommunicatePageChildren.TYPE_INTERACT;
                break;
            case MessageUtil.MESSAGE_TYPE_CONTACT:
                childType = EventRefreshCommunicatePageChildren.TYPE_CONTACT;
                break;
            default:
                childType = null;
                break;
        }
        if (childType == null) return;
        if (isFragmentVisible()) {
            EventBus.getDefault().post(EventRefreshCommunicatePageChildren.newBuilder()
                    .type(childType).build());
        } else {
            pendingRefreshCommunicatePageChildrenType = childType;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventTapBottomItemRefresh event) {
        if (event.getItemType() == EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE
                && event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_PRE_REFRESH) {
            int pageType;
            if (mainVp.getCurrentItem() == 0) {
                pageType = MessageUtil.PAGE_TYPE_IM;
            } else {
                pageType = MessageUtil.PAGE_TYPE_CONTACT;
            }
            EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                    .itemType(EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE)
                    .actionType(EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH)
                    .pageType(pageType)
                    .build());
        }
    }

    public void updateUnReadMessageView() {
        MessageUtil.MessageCount messageCount = MessageUtil.getNewMessageCount(MessageUtil.MESSAGE_LEVEL_MAIN);
        if (messageCount.getContactCount() != 0) {
            tabLayout.showMsg(1, (int) messageCount.getContactCount());
        } else {
            tabLayout.hideMsg(1);
        }
    }

    @Override
    protected void initData() {
        updateUnReadMessageView();
        Router.registerRouterEventBus(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(EventCommunicatePageRouter event) {
        Router.eventBus.removeStickyEvent(event);
        mainVp.setCurrentItem(event.getJumpIndex(), false);
    }
}
